package wdt_qf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.qimencloud.api.scenehu3cgwt0tc.response.WdtOtherOutStockQueryTradeResponse;
import com.qimencloud.api.scenehu3cgwt0tc.response.WdtStockPdQueryTradeResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import wdt_qf.dao.BasicInfoDao;
import wdt_qf.dao.BillIndexDao;
import wdt_qf.dao.StockBillDao;
import wdt_qf.dao.StocksDao;
import wdt_qf.entity.BillIndex;
import wdt_qf.entity.StockBill;
import wdt_qf.entity.qf.BtypeBean;
import wdt_qf.entity.qf.NeedPdgoodsStockBean;
import wdt_qf.entity.qf.StockBean;
import wdt_qf.entity.qf.common.ResultData;
import wdt_qf.entity.qf.pro.Zwj_UpdateCheckTable;
import wdt_qf.entity.qf.query.Gp_BillBatchOrderQuery;
import wdt_qf.entity.qf.result.PtypeInfoRes;
import wdt_qf.entity.qf.result.QfPosGoodsStockQtyRes;
import wdt_qf.service.QfBillService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j(topic = "QfBillServiceImpl")
public class QfBillServiceImpl implements QfBillService {
    @Resource
    private BillIndexDao billIndexDao;
    @Resource
    private StockBillDao stockBillDao;
    @Resource
    private StocksDao stocksDao;
    @Resource
    private BasicInfoDao basicInfoDao;

    @Override
    public ResultData aaddOtherBillToQf(WdtOtherOutStockQueryTradeResponse response) {
        String buserCode = "";
        String kuserCode = "";

        List<WdtOtherOutStockQueryTradeResponse.Array> stockoutList = response.getStockoutList();
        for (int i = 0; i < stockoutList.size(); i++) {
            WdtOtherOutStockQueryTradeResponse.Array array = stockoutList.get(i);
            String billCode = array.getOrder_no();
            //根据单号查询千方是否已经存在这个单据
            BillIndex billIndexByBillCode = billIndexDao.getBillIndexByBillCode(billCode);
            if (BeanUtil.isNotEmpty(billIndexByBillCode)) {
                log.error(billCode + "单号在千方已经存在,无需再次插入数据！");
                continue;
            }
            if (array.getWarehouse_no().equals("XLTX")) {
                buserCode = "00001";
                kuserCode = "01";
            } else {
                buserCode = "00002";
                kuserCode = "02";
            }
            int erec = 0;
            StockBean stockInfoByUserCode = stocksDao.getStockInfoByUserCode(kuserCode);
            BtypeBean btypeByUserCode = basicInfoDao.getBtypeByUserCode(buserCode);
            BillIndex billIndex = new BillIndex();
            billIndex.setBillCode(billCode)
                    .setBillDate(array.getConsign_time().substring(0, 10))
                    .setComment("旺店通单据")
                    .setBRec(btypeByUserCode.getRec() + "")
                    .setERec("0")
                    .setKRec(stockInfoByUserCode.getRec() + "")
                    .setKRec2("0")
                    .setChecke("0")
                    .setIFChecked(false)
                    .setBillE("0")
                    .setTotalmoney(array.getGoods_total_amount())
                    .setTotalinmoney(array.getGoods_total_amount())
                    .setTotalqty(array.getGoods_count())
                    .setBenefitMoney("0")
                    .setTax("-10.00")
                    .setPeriod(1)
                    .setExplain("")
                    .setRedWord("0")
                    .setDraft("1")
                    .setOrderId(0)
                    .setDepartment("0")
                    .setPosid("0")
                    .setArea("0")
                    .setAuditingDate(null)
                    .setMoneyDate(null)
                    .setJsYetotal(array.getGoods_total_amount())
                    .setJsFlag("")
                    .setQualityStatus("0")
                    .setGspId("0")
                    .setPriceDiff("0")
                    .setUniqueBillid(stocksDao.getUniqueBillid())
                    .setNextBillid(null)
                    .setInvoiceId(null)
                    .setBillStatus("0")
                    .setPrintTime("0")
                    .setNSysFlag("0")
                    .setOfficeId("0")
                    .setOutStockLaw("z")
                    .setSendWay("")
                    .setIsRedWordNew("0")
                    .setBillDetailCount(array.getDetails_list().size())
                    .setCanDelete("1")
                    .setHandoverTime(null)
                    .setInvoice("")
                    .setStatus("0")
                    .setFlag(0)
                    .setVipCardID(0)
                    .setChangeID(btypeByUserCode.getChangeId())
                    .setAuditid(0)
                    .setJSBRec(btypeByUserCode.getRec())
                    .setBillTime(array.getConsign_time())
                    .setORec(0)
                    .setORec2(0)
                    .setInvoiceCode("");
            int insert = billIndexDao.insert(billIndex);
            int billId = billIndexDao.getBillId(billCode);
            int ord = 1;
            for (int i1 = 0; i1 < array.getDetails_list().size(); i1++) {
                WdtOtherOutStockQueryTradeResponse.Array.DetailsListBean detailsListBean = array.getDetails_list().get(i1);
                for (int i2 = 0; i2 < detailsListBean.getPosition_list().size(); i2++) {
                    WdtOtherOutStockQueryTradeResponse.Array.position_listBean positionListBean =
                            detailsListBean.getPosition_list().get(i2);
                    String _ptypeUserCode = detailsListBean.getSpec_no();
                    PtypeInfoRes ptypeInfoRes = stocksDao.getPtypeByUserCode(_ptypeUserCode);
                    Gp_BillBatchOrderQuery billBatchOrderQuery = new Gp_BillBatchOrderQuery();
                    billBatchOrderQuery.setPrec(ptypeInfoRes.getRec()).setKrec(stockInfoByUserCode.getRec())
                            .setUserRec(erec);
                    List<QfPosGoodsStockQtyRes> qfPosGoodsStockQtyRes = stocksDao.Gp_BillBatchOrder(billBatchOrderQuery);
                    List<QfPosGoodsStockQtyRes> qfPosGoodsStockQtyResNoStopUse = qfPosGoodsStockQtyRes.stream().filter(f -> f.getStopUse() == 0).collect(Collectors.toList());
                    //升序排列(将库存进行排序)
                    qfPosGoodsStockQtyResNoStopUse = qfPosGoodsStockQtyResNoStopUse.stream().sorted(Comparator.comparing(QfPosGoodsStockQtyRes::getQty)).collect(Collectors.toList());
                    if (CollUtil.isEmpty(qfPosGoodsStockQtyResNoStopUse)) {
                        log.error("单据编号:" + billCode + "--" + JSON.toJSONString(_ptypeUserCode) + "商品库存不足" + "销售数量为：" + detailsListBean.getGoods_count());
                        return null;
                    }
                    double _rowTotalMoney = Double.parseDouble(detailsListBean.getGoods_count()) * Double.parseDouble(detailsListBean.getSell_price());
                    //TODO 调用计算库存方法
                    List<QfPosGoodsStockQtyRes> createRetailBillStockList =
                            this.getCreateRetailBillStockListByQtyAndJobnumber(qfPosGoodsStockQtyResNoStopUse,
                                    Double.parseDouble(positionListBean.getPosition_goods_count()),
                                    positionListBean.getBatch_no());
                    StockBill stockBill = new StockBill();
                    for (QfPosGoodsStockQtyRes posGoodsStockQtyRes : createRetailBillStockList) {
                        stockBill.setBillID(billId)
                                .setOrd(ord)
                                .setPRec(posGoodsStockQtyRes.getPRec())
                                .setKRec(stockInfoByUserCode.getRec())
                                .setGRec(Integer.parseInt(posGoodsStockQtyRes.getGRec()))
                                .setAssQty(posGoodsStockQtyRes.getRetailBillQty())
                                .setQty(posGoodsStockQtyRes.getRetailBillQty())
                                .setPrice(Double.parseDouble(detailsListBean.getSell_price()))
                                .setAssPrice(Double.parseDouble(detailsListBean.getSell_price()))
                                .setTotal(posGoodsStockQtyRes.getRetailBillQty() * Double.parseDouble(detailsListBean.getSell_price()))
                                .setJobNumber(posGoodsStockQtyRes.getJobNumber())
                                .setOutFactoryDate(posGoodsStockQtyRes.getOutFactoryDate())
                                .setValidityPeriod(posGoodsStockQtyRes.getValidityPeriod())
                                .setComment("")
                                .setCostPrice(posGoodsStockQtyRes.getPrice())
                                .setEligible("合格")
                                .setUnit(1)
                                .setUnitRate(1.0)
                                .setProviderid(posGoodsStockQtyRes.getProviderId())
                                .setPtypesource(0)
                                .setStockUniqueid(posGoodsStockQtyRes.getStockUniqueid())
                                .setJobCode(posGoodsStockQtyRes.getJobcode())
                                .setStopUse(posGoodsStockQtyRes.getStopUse())
                                .setGermJobNumber(posGoodsStockQtyRes.getGermJobNumber())
                                .setCheckReportNo(posGoodsStockQtyRes.getCheckReportNo())
                                .setRetailPrice("0.0")
                                .setPromotionID("")
                                .setPromotionBillCode("")
                                .setPromotionComment("")
                                .setPromotionBillID("0")
                                .setChangeID(ptypeInfoRes.getPtypeChange() + "")
                                .setSNTEXT("")
                                .setGJobID("0");
                        stockBillDao.insert(stockBill);
                        ord = ord + 1;
                    }
                }
            }
        }

        return new ResultData(1, "成功生成单据", null);
    }

    @Override
    public ResultData addStockZdPdToQf(WdtStockPdQueryTradeResponse response) {
        String kuserCode = "";
        for (int i = 0; i < response.getPd_list().size(); i++) {
            WdtStockPdQueryTradeResponse.Array array = response.getPd_list().get(i);
            kuserCode = array.getWarehouse_no();
            if (!kuserCode.equals("SH") && !kuserCode.equals("XLTX")) {
                log.error("当前盘点单千方仓库不存在");
                continue;
            }
            if (kuserCode.equals("XLTX")) {
                kuserCode = "01";
            } else {
                kuserCode = "02";
            }
            StockBean stockInfoByUserCode = stocksDao.getStockInfoByUserCode(kuserCode);
            for (int i1 = 0; i1 < array.getDetails_list().size(); i1++) {
                WdtStockPdQueryTradeResponse.Array.DetailsListBean detailsListBean = array.getDetails_list().get(i1);
                PtypeInfoRes ptypeInfoRes = stocksDao
                        .getPtypeByUserCode(detailsListBean.getSpec_no());
                NeedPdgoodsStockBean needPdgoodsStockBean = stocksDao.getNeedPdGoodsStock(detailsListBean.getSpec_no());
                Zwj_UpdateCheckTable zwjUpdateCheckTable = new Zwj_UpdateCheckTable();
                zwjUpdateCheckTable
                        .setKrec(stockInfoByUserCode.getRec())
                        .setPrec(ptypeInfoRes.getRec())
                        .setJobnumber("")
                        .setOutFactoryDate(null)
                        .setValidityPeriod(null)
                        .setUnit(ptypeInfoRes.getUnit1())
                        .setRate(1.0)
                        .setQty(needPdgoodsStockBean.getQty())
                        .setCheckqty(Double.parseDouble(detailsListBean.getNew_num()))
                        .setStopUse(0)
                        .setJobCode("")
                        .setSzComment("")
                        .setGermJobNumber("")
                        .setCheckReportNo("")
                        .setCheckmode("1")
                        .setUnit(needPdgoodsStockBean.getUnit1())
                        .setUqty(Double.parseDouble(detailsListBean.getNew_num()))
                        .setU1qty(0.0)
                        .setU2qty(0.0)
                        .setPosRetailPrice(0.0)
                        .setGjobId("0");
                stocksDao.zdpd(zwjUpdateCheckTable);
            }

        }
        return null;
    }


    /**
     * @param stockQtyResList1 当前库存剩余数量
     * @param saleQty          当前单据需要销售的数量
     * @param jobnumber        批次号
     * @return
     */
    public List<QfPosGoodsStockQtyRes> getCreateRetailBillStockListByQtyAndJobnumber(List<QfPosGoodsStockQtyRes> stockQtyResList1,
                                                                                     double saleQty, String jobnumber) {
        //TODO  进来，首先进行批号过滤
        List<QfPosGoodsStockQtyRes> stockQtyResList = new ArrayList<>();
        for (QfPosGoodsStockQtyRes qfPosGoodsStockQtyRes : stockQtyResList1) {
            if (qfPosGoodsStockQtyRes.getJobNumber().equals(jobnumber)) {
                stockQtyResList.add(qfPosGoodsStockQtyRes);
            }
        }
        //进来首先判断下可销库存数量是否够,如果不够直接返回null
        double _canSaleStockQty = 0;
        for (int i = 0; i < stockQtyResList.size(); i++) {
            QfPosGoodsStockQtyRes qfPosGoodsStockQtyRes = stockQtyResList.get(i);
            _canSaleStockQty = qfPosGoodsStockQtyRes.getQty() + _canSaleStockQty;
        }
        if (_canSaleStockQty < saleQty) {
            //log.error( "getCreateRetailBillStockList方法"+ "商品库存不足" + "销售数量为：" + saleQty);
            return null;
        }
        //TODO  库存够,执行库存拆分
        List<QfPosGoodsStockQtyRes> resultList = new ArrayList<>();
        double _totalQty = 0;
        double _alreadyQty = 0;//已经赋值数量
        //首先先将所有的 RetailBillQty 赋值为销售的数量
        for (int i = 0; i < stockQtyResList.size(); i++) {
            QfPosGoodsStockQtyRes qfPosGoodsStockQtyRes = stockQtyResList.get(i);
            qfPosGoodsStockQtyRes.setRetailBillQty(saleQty);
            stockQtyResList.set(i, qfPosGoodsStockQtyRes);
        }
        for (int i = 0; i < stockQtyResList.size(); i++) {
            QfPosGoodsStockQtyRes qfPosGoodsStockQtyRes = stockQtyResList.get(i);
            _totalQty = qfPosGoodsStockQtyRes.getQty() + _totalQty;
            //当前库存累加数量大于销售数量时候,需要吧list 返回
            if (_totalQty >= saleQty) {
                //美团的销售数量-已记录数量其实就等于当前库存需要出的数量
                qfPosGoodsStockQtyRes.setRetailBillQty(saleQty - _alreadyQty);
                resultList.add(qfPosGoodsStockQtyRes);
                return resultList;
            } else {
                //需要将当前库存的数量,赋值成生成零售单的数量
                qfPosGoodsStockQtyRes.setRetailBillQty(qfPosGoodsStockQtyRes.getQty());
                resultList.add(qfPosGoodsStockQtyRes);
                _alreadyQty = _alreadyQty + qfPosGoodsStockQtyRes.getQty();
            }
        }
        return null;
    }
}
